// API连接测试工具
import axios from 'axios'

// 测试API连接状态
export async function testApiConnection(baseUrl) {
    const results = {
        success: false,
        baseUrl,
        tests: [],
        summary: {}
    }

    console.log(`🔍 开始测试API连接: ${baseUrl}`)

    // 测试1: 基础连接测试
    try {
        const startTime = Date.now()
        const response = await axios.get(`${baseUrl}`, { timeout: 5000 })
        const responseTime = Date.now() - startTime

        results.tests.push({
            name: '基础连接',
            success: true,
            status: response.status,
            responseTime: `${responseTime}ms`,
            message: '连接成功'
        })

        console.log(`✅ 基础连接成功 - 响应时间: ${responseTime}ms`)
    } catch (error) {
        results.tests.push({
            name: '基础连接',
            success: false,
            error: error.message,
            message: '连接失败'
        })

        console.log(`❌ 基础连接失败: ${error.message}`)
    }

    // 测试2: 健康检查端点
    try {
        const startTime = Date.now()
        const response = await axios.get(`${baseUrl}health`, { timeout: 5000 })
        const responseTime = Date.now() - startTime

        results.tests.push({
            name: '健康检查',
            success: true,
            status: response.status,
            responseTime: `${responseTime}ms`,
            message: '健康检查通过'
        })

        console.log(`✅ 健康检查成功 - 响应时间: ${responseTime}ms`)
    } catch (error) {
        results.tests.push({
            name: '健康检查',
            success: false,
            error: error.message,
            message: '健康检查失败'
        })

        console.log(`❌ 健康检查失败: ${error.message}`)
    }

    // 测试3: Swagger文档端点
    try {
        const startTime = Date.now()
        const response = await axios.get(`${baseUrl}swagger`, { timeout: 5000 })
        const responseTime = Date.now() - startTime

        results.tests.push({
            name: 'Swagger文档',
            success: true,
            status: response.status,
            responseTime: `${responseTime}ms`,
            message: 'Swagger文档可访问'
        })

        console.log(`✅ Swagger文档测试成功 - 响应时间: ${responseTime}ms`)
    } catch (error) {
        results.tests.push({
            name: 'Swagger文档',
            success: false,
            error: error.message,
            message: 'Swagger文档不可访问'
        })

        console.log(`❌ Swagger文档测试失败: ${error.message}`)
    }

    // 测试4: 供应商API端点
    try {
        const startTime = Date.now()
        const response = await axios.get(`${baseUrl}api/Supplier/list`, {
            timeout: 5000,
            params: { PageIndex: 1, PageSize: 1 }
        })
        const responseTime = Date.now() - startTime

        results.tests.push({
            name: '供应商API',
            success: true,
            status: response.status,
            responseTime: `${responseTime}ms`,
            message: '供应商API可访问',
            data: response.data
        })

        console.log(`✅ 供应商API测试成功 - 响应时间: ${responseTime}ms`)
        console.log('API响应数据:', response.data)
    } catch (error) {
        results.tests.push({
            name: '供应商API',
            success: false,
            error: error.message,
            message: '供应商API不可访问'
        })

        console.log(`❌ 供应商API测试失败: ${error.message}`)
    }

    // 生成摘要
    const successCount = results.tests.filter(test => test.success).length
    const totalTests = results.tests.length

    results.summary = {
        totalTests,
        successCount,
        successRate: `${((successCount / totalTests) * 100).toFixed(1)}%`,
        overallSuccess: successCount === totalTests
    }

    results.success = results.summary.overallSuccess

    console.log('📊 API连接测试摘要:', results.summary)
    return results
}

// 测试多个API端点
export async function testMultipleEndpoints(endpoints) {
    const results = {
        success: false,
        endpoints: [],
        summary: {}
    }

    console.log(`🔍 开始测试多个API端点: ${endpoints.length} 个`)

    for (const endpoint of endpoints) {
        try {
            const startTime = Date.now()
            const response = await axios.get(endpoint.url, {
                timeout: 5000,
                params: endpoint.params || {}
            })
            const responseTime = Date.now() - startTime

            results.endpoints.push({
                name: endpoint.name,
                url: endpoint.url,
                success: true,
                status: response.status,
                responseTime: `${responseTime}ms`,
                message: '连接成功',
                data: response.data
            })

            console.log(`✅ ${endpoint.name} 测试成功 - 响应时间: ${responseTime}ms`)
        } catch (error) {
            results.endpoints.push({
                name: endpoint.name,
                url: endpoint.url,
                success: false,
                error: error.message,
                message: '连接失败'
            })

            console.log(`❌ ${endpoint.name} 测试失败: ${error.message}`)
        }
    }

    // 生成摘要
    const successCount = results.endpoints.filter(endpoint => endpoint.success).length
    const totalEndpoints = results.endpoints.length

    results.summary = {
        totalEndpoints,
        successCount,
        successRate: `${((successCount / totalEndpoints) * 100).toFixed(1)}%`,
        overallSuccess: successCount === totalEndpoints
    }

    results.success = results.summary.overallSuccess

    console.log('📊 多端点测试摘要:', results.summary)
    return results
}

// 测试网络延迟
export async function testNetworkLatency(baseUrl, iterations = 3) {
    const latencies = []

    console.log(`🔍 开始测试网络延迟: ${baseUrl} (${iterations} 次)`)

    for (let i = 0; i < iterations; i++) {
        try {
            const startTime = Date.now()
            await axios.get(`${baseUrl}`, { timeout: 10000 })
            const latency = Date.now() - startTime
            latencies.push(latency)

            console.log(`第 ${i + 1} 次测试 - 延迟: ${latency}ms`)
        } catch (error) {
            console.log(`第 ${i + 1} 次测试失败: ${error.message}`)
        }

        // 等待1秒再进行下一次测试
        if (i < iterations - 1) {
            await new Promise(resolve => setTimeout(resolve, 1000))
        }
    }

    if (latencies.length > 0) {
        const avgLatency = latencies.reduce((sum, latency) => sum + latency, 0) / latencies.length
        const minLatency = Math.min(...latencies)
        const maxLatency = Math.max(...latencies)

        console.log('📊 网络延迟测试结果:', {
            average: `${avgLatency.toFixed(0)}ms`,
            min: `${minLatency}ms`,
            max: `${maxLatency}ms`,
            samples: latencies.length
        })

        return {
            success: true,
            average: avgLatency,
            min: minLatency,
            max: maxLatency,
            samples: latencies
        }
    } else {
        console.log('❌ 网络延迟测试失败，没有成功样本')
        return {
            success: false,
            error: '没有成功样本'
        }
    }
} 